<template>
  <div class="yunying-billing-management">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>对账单管理</span>
          <div>
            <el-button type="primary" @click="showGenerateDialog">生成对账单</el-button>
            <el-button type="success" @click="showBatchGenerateDialog">批量生成</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" size="small">
          <el-form-item label="供应商ID">
            <el-input v-model="searchForm.supplierId" placeholder="供应商ID"></el-input>
          </el-form-item>
          <el-form-item label="对账单状态">
            <el-select v-model="searchForm.status" placeholder="全部">
              <el-option label="全部" value=""></el-option>
              <el-option label="待确认" value="pending"></el-option>
              <el-option label="已确认" value="confirmed"></el-option>
              <el-option label="有争议" value="disputed"></el-option>
              <el-option label="已结算" value="settled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker v-model="searchForm.startDate" type="date" placeholder="开始日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker v-model="searchForm.endDate" type="date" placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchBillings">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 对账单列表 -->
      <el-table v-loading="loading" :data="billingList.records" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="statementNo" label="对账单编号" width="180"></el-table-column>
        <el-table-column prop="supplierId" label="供应商ID"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
        <el-table-column prop="startDate" label="开始日期"></el-table-column>
        <el-table-column prop="endDate" label="结束日期"></el-table-column>
        <el-table-column prop="totalAmount" label="总金额" formatter="formatCurrency"></el-table-column>
        <el-table-column prop="commissionAmount" label="佣金金额" formatter="formatCurrency"></el-table-column>
        <el-table-column prop="paymentAmount" label="实付金额" formatter="formatCurrency"></el-table-column>
        <el-table-column prop="statusDesc" label="状态"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="small" @click="viewDetail(scope.row.id)">查看详情</el-button>
            <el-button
              size="small"
              type="primary"
              @click="showUpdateStatusDialog(scope.row.id, scope.row.status)"
            >
              更新状态
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model="pagination.pageNum"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="billingList.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 对账单详情弹窗 -->
    <el-dialog :visible.sync="detailDialogVisible" title="对账单详情" width="80%">
      <div v-if="billingDetail" class="billing-detail">
        <div class="detail-header">
          <div class="detail-item"><span class="label">对账单编号：</span>{{ billingDetail.statementNo }}</div>
          <div class="detail-item"><span class="label">供应商ID：</span>{{ billingDetail.supplierId }}</div>
          <div class="detail-item"><span class="label">供应商名称：</span>{{ billingDetail.supplierName }}</div>
          <div class="detail-item"><span class="label">对账周期：</span>{{ billingDetail.startDate }} 至 {{ billingDetail.endDate }}</div>
          <div class="detail-item"><span class="label">总金额：</span>{{ formatCurrency(billingDetail.totalAmount) }}</div>
          <div class="detail-item"><span class="label">佣金金额：</span>{{ formatCurrency(billingDetail.commissionAmount) }}</div>
          <div class="detail-item"><span class="label">实付金额：</span>{{ formatCurrency(billingDetail.paymentAmount) }}</div>
          <div class="detail-item"><span class="label">状态：</span>{{ billingDetail.statusDesc }}</div>
          <div class="detail-item"><span class="label">备注：</span>{{ billingDetail.remark }}</div>
          <div class="detail-item"><span class="label">创建人：</span>{{ billingDetail.createdBy }}</div>
          <div class="detail-item"><span class="label">创建时间：</span>{{ billingDetail.createdAt }}</div>
        </div>

        <div class="detail-title">对账单明细</div>
        <el-table :data="billingItems.records" style="width: 100%">
          <el-table-column prop="orderNo" label="订单编号"></el-table-column>
          <el-table-column prop="orderTime" label="订单时间"></el-table-column>
          <el-table-column prop="productName" label="商品名称"></el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>
          <el-table-column prop="unitPrice" label="单价" formatter="formatCurrency"></el-table-column>
          <el-table-column prop="totalPrice" label="总价" formatter="formatCurrency"></el-table-column>
          <el-table-column prop="commissionRate" label="佣金率" formatter="formatPercent"></el-table-column>
          <el-table-column prop="commissionAmount" label="佣金金额" formatter="formatCurrency"></el-table-column>
          <el-table-column prop="notes" label="备注"></el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model="itemPagination.pageNum"
            :page-size="itemPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="billingItems.total"
            @size-change="handleItemSizeChange"
            @current-change="handleItemCurrentChange"
          ></el-pagination>
        </div>
      </div>
      <div v-else>加载中...</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 生成对账单弹窗 -->
    <el-dialog :visible.sync="generateDialogVisible" title="生成对账单" width="600px">
      <el-form :model="generateForm" ref="generateForm" :rules="generateRules">
        <el-form-item label="供应商ID" prop="supplierId">
          <el-input v-model="generateForm.supplierId" placeholder="请输入供应商ID"></el-input>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="generateForm.startDate" type="date" placeholder="开始日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="generateForm.endDate" type="date" placeholder="结束日期" style="width: 100%"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateBilling">生成</el-button>
      </div>
    </el-dialog>

    <!-- 批量生成对账单弹窗 -->
    <el-dialog :visible.sync="batchGenerateDialogVisible" title="批量生成对账单" width="600px">
      <div class="batch-generate-container">
        <el-form :model="batchGenerateForm">
          <el-form-item label="供应商ID列表">
            <el-input
              type="textarea"
              v-model="batchGenerateForm.supplierIds"
              placeholder="请输入供应商ID，多个ID以逗号分隔"
              rows="4"
            ></el-input>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker v-model="batchGenerateForm.startDate" type="date" placeholder="开始日期" style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker v-model="batchGenerateForm.endDate" type="date" placeholder="结束日期" style="width: 100%"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchGenerateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="batchGenerateBillings">批量生成</el-button>
      </div>
    </el-dialog>

    <!-- 更新状态弹窗 -->
    <el-dialog :visible.sync="updateStatusDialogVisible" title="更新对账单状态" width="500px">
      <el-form :model="updateStatusForm" ref="updateStatusForm" :rules="updateStatusRules">
        <el-form-item label="当前状态" prop="currentStatus">
          <el-input v-model="updateStatusForm.currentStatus" disabled></el-input>
        </el-form-item>
        <el-form-item label="目标状态" prop="targetStatus">
          <el-select v-model="updateStatusForm.targetStatus" placeholder="请选择目标状态">
            <el-option label="待确认" value="pending"></el-option>
            <el-option label="已确认" value="confirmed"></el-option>
            <el-option label="有争议" value="disputed"></el-option>
            <el-option label="已结算" value="settled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="updateStatusForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateStatusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateBillingStatus">更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import unifiedBillingApi from '@/api/unifiedBillingApi'
import { mapGetters } from 'vuex'

export default {
  name: 'YunyingBillingManagement',
  data() {
    return {
      loading: false,
      searchForm: {
        supplierId: '',
        status: '',
        startDate: '',
        endDate: ''
      },
      pagination: {
        pageNum: 1,
        pageSize: 10
      },
      billingList: {
        total: 0,
        records: []
      },
      detailDialogVisible: false,
      billingDetail: null,
      itemPagination: {
        pageNum: 1,
        pageSize: 10
      },
      billingItems: {
        total: 0,
        records: []
      },
      generateDialogVisible: false,
      generateForm: {
        supplierId: '',
        startDate: '',
        endDate: ''
      },
      generateRules: {
        supplierId: [
          { required: true, message: '请输入供应商ID', trigger: 'blur' },
          { pattern: /^\d+$/, message: '供应商ID必须是数字', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ]
      },
      batchGenerateDialogVisible: false,
      batchGenerateForm: {
        supplierIds: '',
        startDate: '',
        endDate: ''
      },
      updateStatusDialogVisible: false,
      currentBillingId: null,
      updateStatusForm: {
        currentStatus: '',
        targetStatus: '',
        remark: ''
      },
      updateStatusRules: {
        targetStatus: [
          { required: true, message: '请选择目标状态', trigger: 'change' }
        ],
        remark: [
          { min: 0, max: 500, message: '长度不超过 500 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['userType', 'isLoggedIn'])
  },
  created() {
    // 检查登录状态
    if (!this.isLoggedIn) {
      this.$router.push('/login')
      return
    }
    // 设置用户类型到API服务
    unifiedBillingApi.setUserType(this.userType)
    this.fetchBillings()
  },
  methods: {
    fetchBillings() {
      this.loading = true
      // 格式化日期
      const startDate = this.searchForm.startDate
        ? this.formatDate(this.searchForm.startDate)
        : ''
      const endDate = this.searchForm.endDate
        ? this.formatDate(this.searchForm.endDate)
        : ''

      // 构建查询参数
      const queryParams = {
        supplierId: this.searchForm.supplierId ? Number(this.searchForm.supplierId) : null,
        status: this.searchForm.status,
        startDate: startDate,
        endDate: endDate
      }

      unifiedBillingApi
        .getBillingList(
          this.pagination.pageNum,
          this.pagination.pageSize,
          queryParams
        )
        .then((res) => {
          this.billingList = res.data
        })
        .catch((error) => {
          console.error('获取对账单列表失败:', error)
          this.$message.error('获取对账单列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    resetSearch() {
      this.searchForm = {
        supplierId: '',
        status: '',
        startDate: '',
        endDate: ''
      }
      this.fetchBillings()
    },

    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.fetchBillings()
    },

    handleCurrentChange(current) {
      this.pagination.pageNum = current
      this.fetchBillings()
    },

    viewDetail(id) {
      this.detailDialogVisible = true
      this.loading = true
      unifiedBillingApi
        .getBillingDetail(id)
        .then((res) => {
          this.billingDetail = res.data
          // 加载对账单明细
          this.fetchBillingItems(id)
        })
        .catch((error) => {
          console.error('获取对账单详情失败:', error)
          this.$message.error('获取对账单详情失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    fetchBillingItems(statementId) {
      unifiedBillingApi
        .getBillingItems(
          statementId,
          this.itemPagination.pageNum,
          this.itemPagination.pageSize
        )
        .then((res) => {
          this.billingItems = res.data
        })
        .catch((error) => {
          console.error('获取对账单明细失败:', error)
          this.$message.error('获取对账单明细失败')
        })
    },

    handleItemSizeChange(size) {
      this.itemPagination.pageSize = size
      this.fetchBillingItems(this.billingDetail.id)
    },

    handleItemCurrentChange(current) {
      this.itemPagination.pageNum = current
      this.fetchBillingItems(this.billingDetail.id)
    },

    showGenerateDialog() {
      this.generateForm = {
        supplierId: '',
        startDate: '',
        endDate: ''
      }
      this.generateDialogVisible = true
    },

    generateBilling() {
      this.$refs.generateForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const requestData = {
            supplierId: Number(this.generateForm.supplierId),
            startDate: this.formatDate(this.generateForm.startDate),
            endDate: this.formatDate(this.generateForm.endDate)
          }

          unifiedBillingApi
            .generateBilling(requestData)
            .then(() => {
              this.$message.success('对账单生成成功')
              this.generateDialogVisible = false
              this.fetchBillings()
            })
            .catch((error) => {
              console.error('生成对账单失败:', error)
              this.$message.error('生成对账单失败')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    showBatchGenerateDialog() {
      this.batchGenerateForm = {
        supplierIds: '',
        startDate: '',
        endDate: ''
      }
      this.batchGenerateDialogVisible = true
    },

    batchGenerateBillings() {
      // 验证供应商ID列表
      if (!this.batchGenerateForm.supplierIds.trim()) {
        this.$message.error('请输入供应商ID列表')
        return
      }

      if (!this.batchGenerateForm.startDate || !this.batchGenerateForm.endDate) {
        this.$message.error('请选择开始日期和结束日期')
        return
      }

      // 解析供应商ID列表
      const supplierIds = this.batchGenerateForm.supplierIds
        .split(',')
        .map((id) => id.trim())
        .filter((id) => id)
        .map((id) => Number(id))

      // 验证供应商ID是否都是数字
      if (supplierIds.some((id) => isNaN(id))) {
        this.$message.error('供应商ID必须是数字')
        return
      }

      this.loading = true
      const startDate = this.formatDate(this.batchGenerateForm.startDate)
      const endDate = this.formatDate(this.batchGenerateForm.endDate)

      // 构造请求数据
      const requests = supplierIds.map((supplierId) => ({
        supplierId,
        startDate,
        endDate
      }))

      unifiedBillingApi
            .batchGenerateBillings(requests)
        .then((res) => {
          this.$message.success(`批量生成成功，共生成${res.data}个对账单`)
          this.batchGenerateDialogVisible = false
          this.fetchBillings()
        })
        .catch((error) => {
          console.error('批量生成对账单失败:', error)
          this.$message.error('批量生成对账单失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    showUpdateStatusDialog(id, currentStatus) {
      this.currentBillingId = id
      this.updateStatusForm = {
        currentStatus: this.getStatusDesc(currentStatus),
        targetStatus: '',
        remark: ''
      }
      this.updateStatusDialogVisible = true
    },

    updateBillingStatus() {
      this.$refs.updateStatusForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const requestData = {
            statementId: this.currentBillingId,
            targetStatus: this.updateStatusForm.targetStatus,
            remark: this.updateStatusForm.remark
          }

          unifiedBillingApi
            .updateBillingStatus(requestData)
            .then(() => {
              this.$message.success('对账单状态更新成功')
              this.updateStatusDialogVisible = false
              this.fetchBillings()
            })
            .catch((error) => {
              console.error('更新对账单状态失败:', error)
              this.$message.error('更新对账单状态失败')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    formatDate(date) {
      if (!date) return ''
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    getStatusDesc(status) {
      const statusMap = {
        pending: '待确认',
        confirmed: '已确认',
        disputed: '有争议',
        settled: '已结算'
      }
      return statusMap[status] || status
    },

    formatCurrency(row, column, cellValue) {
      if (!cellValue) return '¥0.00'
      return '¥' + cellValue.toFixed(2)
    },

    formatPercent(row, column, cellValue) {
      if (!cellValue) return '0%'
      return (cellValue * 100).toFixed(2) + '%'
    }
  },
  watch: {
    // 监听用户类型变化
    userType(newValue) {
      unifiedBillingApi.setUserType(newValue)
    }
  }
}
</script>

<style scoped>
.yunying-billing-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.billing-detail {
  padding: 10px;
}

.detail-header {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.detail-item {
  width: 33.3%;
  margin-bottom: 10px;
}

.label {
  font-weight: bold;
  margin-right: 10px;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
  margin: 15px 0;
}

.batch-generate-container {
  padding: 10px;
}
</style>